package com.gitee.cashzhang27.test.cloud.oauth.auth.server.extended.configuration;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gitee.cashzhang27.test.cloud.oauth.auth.server.extended.filter.EmailNumberVerifyCodeAuthenticationFilter;
import com.gitee.cashzhang27.test.cloud.oauth.auth.server.extended.filter.PhoneNumberVerifyCodeAuthenticationFilter;
import com.gitee.cashzhang27.test.cloud.oauth.auth.server.extended.filter.UsernamePasswordAuthenticationFilter;
import com.gitee.cashzhang27.test.cloud.oauth.auth.server.extended.handler.LoginSuccessHandler;
import com.gitee.cashzhang27.test.cloud.oauth.auth.server.extended.provider.EmailAuthenticationProvider;
import com.gitee.cashzhang27.test.cloud.oauth.auth.server.extended.provider.PhoneAuthenticationProvider;
import com.gitee.cashzhang27.test.cloud.oauth.auth.server.extended.provider.UsernameAuthenticationProvider;
import com.gitee.cashzhang27.test.cloud.oauth.auth.server.extended.service.AuthUserDetailsService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Primary;
import org.springframework.security.authentication.AuthenticationEventPublisher;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;

/**
 * spring security配置
 *
 * @author Cash Zhang
 * @version v1.0
 * @since 2019/01/26 11:52
 */
@Slf4j
@Primary
@Configuration
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

  @Autowired
  private AuthUserDetailsService authUserDetailsService;

  @Autowired
  private ObjectMapper objectMapper;
  @Autowired
  private ClientDetailsService clientDetailsService;
  @Lazy
  @Autowired
  private AuthorizationServerTokenServices defaultAuthorizationServerTokenServices;
  @Autowired
  private AuthenticationEventPublisher defaultAuthenticationEventPublisher;


  @Override
  @SneakyThrows
  protected void configure(HttpSecurity http) {
    http
        // 配置登陆页/login并允许访问
        .formLogin().permitAll().loginPage("/login")
        .and()
        .logout().logoutUrl("/logout").logoutSuccessUrl("/")
        .and()
        .authorizeRequests()
        .antMatchers(
            "/oauth/**", "/actuator/**").permitAll()
        .anyRequest().authenticated()
        .and().csrf().disable();
  }

  /**
   * 不拦截静态资源
   */
  @Override
  public void configure(WebSecurity web) {
    web.ignoring().antMatchers("/css/**");
  }

  @Bean
  @Override
  @SneakyThrows
  public AuthenticationManager authenticationManagerBean() {
    return super.authenticationManagerBean();
  }

  @Override
  public void configure(AuthenticationManagerBuilder auth) {
    auth.authenticationProvider(phoneAuthenticationProvider());
    auth.authenticationProvider(daoAuthenticationProvider());
    auth.authenticationProvider(emailAuthenticationProvider());
  }

  @Bean
  public PhoneAuthenticationProvider phoneAuthenticationProvider() {
    PhoneAuthenticationProvider phoneAuthenticationProvider = new PhoneAuthenticationProvider();
    // 设置userDetailsService
    phoneAuthenticationProvider.setUserDetailsService(authUserDetailsService);
    // 禁止隐藏用户未找到异常
    phoneAuthenticationProvider.setHideUserNotFoundExceptions(false);
    // 使用BCrypt进行密码的hash
    phoneAuthenticationProvider.setPasswordEncoder(passwordEncoder());
    return phoneAuthenticationProvider;
  }

  @Bean
  public EmailAuthenticationProvider emailAuthenticationProvider() {
    EmailAuthenticationProvider emailAuthenticationProvider = new EmailAuthenticationProvider();
    // 设置userDetailsService
    emailAuthenticationProvider.setUserDetailsService(authUserDetailsService);
    // 禁止隐藏用户未找到异常
    emailAuthenticationProvider.setHideUserNotFoundExceptions(false);
    // 使用BCrypt进行密码的hash
    emailAuthenticationProvider.setPasswordEncoder(passwordEncoder());
    return emailAuthenticationProvider;
  }

  @Bean
  public UsernameAuthenticationProvider daoAuthenticationProvider() {
    UsernameAuthenticationProvider daoAuthenticationProvider = new UsernameAuthenticationProvider();
    // 设置userDetailsService
    daoAuthenticationProvider.setUserDetailsService(authUserDetailsService);
    // 禁止隐藏用户未找到异常
    daoAuthenticationProvider.setHideUserNotFoundExceptions(false);
    // 使用BCrypt进行密码的hash
    daoAuthenticationProvider.setPasswordEncoder(passwordEncoder());
    return daoAuthenticationProvider;
  }

  /**
   * 用户名密码登陆过滤器
   */
  @Bean
  public UsernamePasswordAuthenticationFilter getUsernamePasswordAuthenticationFilter() {
    UsernamePasswordAuthenticationFilter filter = new UsernamePasswordAuthenticationFilter();
    buildFilter(filter);
    filter.setEventPublisher(defaultAuthenticationEventPublisher);
    return filter;
  }

  /**
   * 手机验证码登陆过滤器
   */
  @Bean
  public PhoneNumberVerifyCodeAuthenticationFilter getPhoneLoginAuthenticationFilter() {
    PhoneNumberVerifyCodeAuthenticationFilter filter = new PhoneNumberVerifyCodeAuthenticationFilter();
    buildFilter(filter);
    filter.setEventPublisher(defaultAuthenticationEventPublisher);
    return filter;
  }

  /**
   * 邮箱验证码登陆过滤器
   */
  @Bean
  public EmailNumberVerifyCodeAuthenticationFilter getEmailLoginAuthenticationFilter() {
    EmailNumberVerifyCodeAuthenticationFilter filter = new EmailNumberVerifyCodeAuthenticationFilter();
    buildFilter(filter);
    filter.setEventPublisher(defaultAuthenticationEventPublisher);
    return filter;
  }

  private <T extends AbstractAuthenticationProcessingFilter> void buildFilter(T filter) {
    filter.setAuthenticationManager(this.authenticationManagerBean());
    filter.setAuthenticationSuccessHandler(LoginSuccessHandler.builder()
        .objectMapper(objectMapper)
        .clientDetailsService(clientDetailsService)
        .passwordEncoder(passwordEncoder())
        .defaultAuthorizationServerTokenServices(defaultAuthorizationServerTokenServices)
        .build());
  }

  /**
   * https://spring.io/blog/2017/11/01/spring-security-5-0-0-rc1-released#password-storage-updated
   * Encoded password does not look like BCrypt
   *
   * @return PasswordEncoder
   */
  @Bean
  public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
  }
}
